<template>
  <div>
    <el-dialog v-model="dialogModel" title="选择图片" @close="dialogClose">
      <div class="overflow-auto" style="max-height: 400px;">
        <el-collapse v-model="collapseName" accordion @change="collapseChangeHandle">
          <el-collapse-item v-for="(group, key) in imageLibrary" :key="key" :name="key" :title="group.title">
            <div v-if="openedList.has(key)" class="d-flex flex-wrap">
              <img
                v-for="(item, index) in group.children" :key="index" :src="item.config.attrs.image.href"
                :title="item.title"
                class="mb-2 image-picker image-item" alt=""
                :class="{ 'image-active': item.config.attrs.image.href === activeImageUrl }" @click="activeImageUrl = item.config.attrs.image.href"
              >
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <template #footer>
        <el-button size="default" @click="dialogModel = false">取消</el-button>
        <el-button type="primary" size="default" @click="submitHandle">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import imageLibrary from '../../../editor-draw/library/images'
import { ref, defineProps, onMounted, onBeforeUnmount } from 'vue'
import { storage } from '@utils/storage'

const props = defineProps<{
  resolve(result: string): void,
  reject(error?: Error): void
}>()

onMounted(function () {
  collapseName.value = storage.session.get('YkEditorDrawImagePicker') || []
  collapseChangeHandle(collapseName.value)
})

// region TODO 折叠面板
const collapseName = ref([])

const openedList = ref(new Set())
function collapseChangeHandle (activeNames: string[]) {
  openedList.value = new Set(Array.from(openedList.value).concat(activeNames))
}
// endregion

// region TODO 选择图片
const activeImageUrl = ref<string>(null)
function submitHandle () {
  props.resolve(activeImageUrl.value)
  dialogModel.value = false
}
// endregion

// region TODO 弹窗
const dialogModel = ref(true)
function dialogClose () {
  props.reject()
}
// endregion

onBeforeUnmount(function () {
  storage.session.set('YkEditorDrawImagePicker', collapseName.value)
})
</script>

<style lang="scss" scoped>
.image-picker.image-item {
  width: 80px;
  height: 80px;
  object-fit: contain;
  margin: 8px;
  border: 1px solid #CCCCCC;
  cursor: pointer;
  &.image-active {
    box-shadow: 0 0 0 4px #6C90D9;
  }
}
</style>
